package org.jeecg.modules.alarm.handler.impl;

import com.zhouwr.common.enums.NoticeType;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.alarm.entity.ActuatorNotification;
import org.jeecg.modules.alarm.handler.IActuatorHandle;
import org.jeecg.modules.alarm.service.IActuatorNotificationService;
import org.jeecg.modules.network.entity.NetworkService;
import org.jeecg.modules.network.service.INetworkServiceService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: forallcn-iotps
 * @description:
 * @author: zhouwr
 * @create: 2021-06-17 09:24
 * @version：1.0
 **/
@Slf4j
public class NotificationHandle implements IActuatorHandle {
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private INetworkServiceService networkService;
    @Autowired
    private IActuatorNotificationService notificationService;

    public NotificationHandle() {
        this.sysBaseAPI = (ISysBaseAPI) SpringContextUtils.getBean(ISysBaseAPI.class);
        this.networkService = (INetworkServiceService) SpringContextUtils.getBean(INetworkServiceService.class);
        this.notificationService = (IActuatorNotificationService) SpringContextUtils.getBean(IActuatorNotificationService.class);
    }

    @Override
    public boolean invoke(String actuatorId, Map<String, Object> dataMap) {
        try {
            /* 1、根据执行器id，获取系统消息配置信息，执行器的id和消息通知id一值 */
            ActuatorNotification notification = notificationService.getById(actuatorId);
            /* 2、判断消息类型，网络服务消息在iot模块中，其它为系统消息 */
            if (notification.getNoticeType().equals(NoticeType.INTERNET_SERVICE)) {
                // 获取网络服务
                String networkServiceId = notification.getNoticeConfigId();
                final NetworkService networkService = this.networkService.getById(networkServiceId);
            } else {
                /* 3、其它为系统消息：根据消息模板code，获取去系统消息模板 */
                log.info("alarmRecordIntoMap >>>>>> {}", dataMap);
                sysBaseAPI.sendMessage(
                        // noticeTemplateCode 通知模板标识
                        notification.getNoticeTemplateCode(),
                        // 消息配置
                        notification.getNoticeConfigId(),
                        // 消息数据集，Map<String, Object> 转化为 Map<String, String>
                        dataMap.entrySet().stream()
                                .collect(Collectors.toMap(Map.Entry::getKey, t -> t.getValue().toString())));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
